﻿@model WebApp.Models.WaterManualRecord
@{
  ViewData["Title"] = "抄表记录";
  ViewData["PageName"] = "WaterManualRecords_Index";
  ViewData["Heading"] = "<i class='fal fa-window text-primary'></i>  抄表记录";
  ViewData["Category1"] = "收费管理";
  ViewData["PageDescription"] = "";
}
@section HeadBlock {
  <link href="@Fingerprint.Tag("/Content/css/notifications/toastr/toastr.css")" rel="stylesheet" />
  <link href="@Fingerprint.Tag("/Scripts/easyui/themes/insdep/easyui.css")" rel="stylesheet" />
  <link href="@Fingerprint.Tag("/Content/css/formplugins/bootstrap-daterangepicker/bootstrap-daterangepicker.css")" rel="stylesheet" />
  <link href="@Fingerprint.Tag("/Scripts/plugin/jquery.fileuploader/jquery.fileuploader.min.css")" rel="stylesheet" />
  <link href="@Fingerprint.Tag("/Scripts/plugin/jquery.fileuploader/jquery.fileuploader-theme-dragdrop.css")" rel="stylesheet" />
  <link href="@Fingerprint.Tag("/Scripts/plugin/jquery.fileuploader/font/font-fileuploader.css")" rel="stylesheet" />
}
<div class="row">
  <div class="col-lg-12 col-xl-12">
    <div id="panel-1" class="panel">
      <div class="panel-hdr">
        <h2>
          抄表记录
        </h2>
        <div class="panel-toolbar">
          <button class="btn btn-panel bg-transparent fs-xl w-auto h-auto rounded-0" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"><i class="fal fa-window-minimize"></i></button>
          <button class="btn btn-panel bg-transparent fs-xl w-auto h-auto rounded-0" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"><i class="fal fa-expand"></i></button>
          @*<button class="btn btn-panel bg-transparent fs-xl w-auto h-auto rounded-0" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"><i class="fal fa-trash-alt"></i></button>*@
        </div>

      </div>
      <div class="panel-container enable-loader show">
        <div class="loader"><i class="fal fa-spinner-third fa-spin-4x fs-xxl"></i></div>
        <div class="panel-content py-2 rounded-bottom border-faded border-left-0 border-right-0  text-muted bg-faded bg-subtlelight-fade">
          <div class="row no-gutters align-items-center">
            <div class="col">
              <!-- 开启授权控制请参考 @@if (Html.IsAuthorize("Create") -->
              <div class="btn-group btn-group-sm">
                <button name="searchbutton" class="btn btn-default"> <span class="fal fa-search mr-1"></span> @Html.L("Refresh") </button>
              </div>
              <div class="btn-group btn-group-sm">
                <button name="appendbutton" class="btn btn-default"> <span class="fal fa-plus mr-1"></span> @Html.L("Add") </button>
              </div>
              <div class="btn-group btn-group-sm">
                <button name="deleterowbutton" disabled class="btn btn-default"> <span class="fal fa-trash-alt mr-1"></span> @Html.L("Delete") </button>
              </div>
              <div class="btn-group btn-group-sm">
                <button name="savechangesbutton" disabled class="btn btn-success"> <span class="fal fa-save mr-1"></span> @Html.L("Save") </button>
              </div>
      
           
              <div class="btn-group btn-group-sm ">
                <button name="exportexcelbutton" class="btn btn-default"> <span class="fal fa-file-excel mr-1"></span>  @Html.L("Export") </button>
              </div>
              <div class="btn-group btn-group-sm ">
                <button name="helpbutton" class="btn btn-default"> <span class="fal fa-question-circle mr-1"></span> @Html.L("Help") </button>
              </div>
            </div>
          </div>
        </div>
        <div class="panel-content">
          <div class="table-responsive">
            <table id="watermanualrecords_datagrid">
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

@section ScriptsBlock {
  @{ Html.RenderPartial("_ImportWindow", new ViewDataDictionary { { "EntityName", "WaterManualRecord" } }); }
  @{ Html.RenderPartial("_PopupDetailFormView", new WebApp.Models.WaterManualRecord()); }
  <script src="@Fingerprint.Tag("/Scripts/plugin/numeral/numeral.min.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/plugin/moment/moment-with-locales.min.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/plugin/jquery.fileuploader/jquery.fileuploader.min.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/notifications/toastr/toastr.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/formplugins/bootstrap-daterangepicker/bootstrap-daterangepicker.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/easyui/jquery.easyui.min.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/easyui/plugins/datagrid-filter.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/easyui/locale/easyui-lang-zh_CN.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/jquery.easyui.component.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/jquery.extend.formatter.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/jquery.custom.extend.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/plugin/jquery.serializejson/jquery.serializejson.min.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/plugin/filesaver/FileSaver.min.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/plugin/filesaver/jquery.fileDownload.js")"></script>
  

  <script type="text/javascript">
    //绑定按钮事件
    $('button[name="searchbutton"]').on('click', reloadData);
    $('button[name="appendbutton"]').on('click', appendData);
    $('button[name="deleterowbutton"]').on('click', deleteRow);
    $('button[name="exportexcelbutton"]').on('click', exportExcel);
    $('button[name="importexcelbutton"]').on('click', () => {
      importexcel('WaterManualRecord')
    });
    $('button[name="downloadtemplatebutton"]').on('click', () => {
      downloadtemplate()
    });

    $('button[name="savechangesbutton"]').on('click', () => {
      acceptChanges()
    });
    //下载Excel导入模板
    function downloadtemplate() {
      //默认模板路径存放位置
      const url = '/WaterManualRecords/DownloadTemplate';
      $.fileDownload(url)
        .done(() => {
          //console.log('file download a success!');
          toastr.success('模板下载完成!');
        })
        .fail(() => {
          $.messager.alert('下载模板失败', '没有下载到导入模板!', 'error');
        });
    }

    //全屏事件
    document.addEventListener('panel.onfullscreen', () => {
         $dg.datagrid('resize');
     });
      //是否强制从后台取值
      const REQUIRBACKEND = false;
      //是否开启行内编辑
      const EDITINLINE = false;
      var watermanualrecord = {};

       //执行导出下载Excel
       function exportExcel() {
                const filterRules = JSON.stringify($dg.datagrid('options').filterRules);
                //console.log(filterRules);
                const dialog = bootbox.dialog({
                    message: '<div class="text-center"><i class="fal fa-spinner fa-pulse fa-lg mr-1"></i> 正在执行...</div>',
                    closeButton: false
                 });
                let formData = new FormData();
                formData.append('filterRules', filterRules);
                formData.append('sort', 'Id');
                formData.append('order', 'asc');
                $.postDownload('/WaterManualRecords/ExportExcel', formData).then(res => {
                    setTimeout(() => {
                       dialog.modal('hide')
                     }, 300);
                    toastr.success('导出成功!');
                }).catch(err => {
                    setTimeout(() => {
                       dialog.modal('hide')
                     }, 300);
                    $.messager.alert('导出失败', err.statusText, 'error');
                });

        }
        //显示帮助信息
        function dohelp() {
            toastr.info('有问题请联系管理员 <br><i class="fa fa-envelope-o" aria-hidden="true"></i> : demo@admin.com','帮助');
        }
    var editIndex = undefined;

    function reload() {
      reloadData();
    }
       //重新加载数据
       function reloadData() {
            $dg.datagrid('unselectAll');
            $dg.datagrid('uncheckAll');
            $dg.datagrid('reload');
       }
    //新增记录
    async function appendData() {
       watermanualrecord = {  };
        //需要后台创建对象
       if (REQUIRBACKEND) {
         watermanualrecord = await $.get('/WaterManualRecords/NewItem');
       }
           //弹出新增窗口
           openwatermanualrecorddetailwindow(watermanualrecord, 'Added');
    }
    //删除编辑的行
    function deleteRow() {
    deleteChecked();
    }
    //删除选中的行
    function deleteChecked() {
        const checked = $dg.datagrid('getChecked').filter(item=>item.Id!=null && item.Id > 0).map(item => {
                   return item.Id;
                });;
        if (checked.length > 0) {
              deleteRows(checked);
         } else {
                $.messager.alert('提示', '请先选择要删除的记录!','question');
         }
     }
    //执行删除
    function deleteRows(selected){
      $.messager.confirm('确认', `你确定要删除这 <span class='badge badge-icon position-relative'>${selected.length} </span> 行记录?`, result => {
       if (result) {
         $.post('/WaterManualRecords/DeleteChecked', { id: selected })
                         .done(response => {
                                if (response.success) {
                                    toastr.error(`成功删除 [${selected.length}] 行记录`);
                                    reloadData();
                                } else {
                                    $.messager.alert('错误', response.err,'error');
                                }
                          })
                          .fail((jqXHR, textStatus, errorThrown) => {
                             $.messager.alert('异常', `${jqXHR.status}: ${jqXHR.statusText} `, 'error');
                          });
        }
      });
    }
    //弹出明细信息
    async function showdetailsWindow(id,index) {
        const watermanualrecord = $dg.datagrid('getRows')[index];
        if (REQUIRBACKEND) {
           watermanualrecord = await $.get('/WaterManualRecords/GetItem/' + id);
        }
        openwatermanualrecorddetailwindow(watermanualrecord,'Modified');
    }
    var editIndex = undefined;
    //关闭编辑状态
    function endEditing() {
      if (editIndex === undefined) {
        return true;
      }
      if ($dg.datagrid('validateRow', editIndex)) {
        $dg.datagrid('endEdit', editIndex);
        return true;
      } else {
        const invalidinput = $('input.validatebox-invalid', $dg.datagrid('getPanel'));
        const fieldnames = invalidinput.map((index, item) => {
          return $(item).attr('placeholder') || $(item).attr('id');
        });
        $.messager.alert('提示', `${Array.from(fieldnames)} 输入有误.`, 'error');
        return false;
      }
    }

    //单击列开启编辑功能
    function onClickCell(index, field) {

      if (editIndex !== index) {
        $("button[name*='savechangesbutton']").prop('disabled', false);
        if (endEditing()) {
          $dg.datagrid('selectRow', index)
            .datagrid('beginEdit', index);
          hook = true;
          editIndex = index;
          const ed = $dg.datagrid('getEditor', { index: index, field: field });
          if (ed) {
            ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
          }
        } else {
          $dg.datagrid('selectRow', editIndex);
        }
      }
    }
    //提交保存后台数据库
    function acceptChanges() {
      if (endEditing()) {
        if ($dg.datagrid('getChanges').length > 0) {
          const inserted = $dg.datagrid('getChanges', 'inserted').map(item => {
            item.TrackingState = 1;
            return item;
          });
          const updated = $dg.datagrid('getChanges', 'updated').map(item => {
            item.TrackingState = 2
            return item;
          });
          const deleted = $dg.datagrid('getChanges', 'deleted').map(item => {
            item.TrackingState = 3
            return item;
          });
          //过滤已删除的重复项
          const changed = inserted.concat(updated.filter(item => {
            return !deleted.includes(item);
          })).concat(deleted);
          //console.table(changed);
          $.post('/WaterManualRecords/AcceptChanges', { watermanualrecords: changed })
            .done(response => {
              //console.log(response);
              if (response.success) {
                toastr.success('保存成功');
                $dg.datagrid('acceptChanges');
                reloadData();
                hook = false;
              } else {
                $.messager.alert('错误', response.err, 'error');
              }
            })
            .fail((jqXHR, textStatus, errorThrown) => {
              $.messager.alert('异常', `${jqXHR.status}: ${jqXHR.statusText} `, 'error');
            });
        }
      }
    }
    //初始化定义datagrid
    var $dg = $('#watermanualrecords_datagrid');
    $(() => {
        //定义datagrid结构
      $dg.datagrid({
       height:670,
        pageSize:15,
                        rownumbers:true,
                        checkOnSelect:false,
                        selectOnCheck:false,
                        idField:'Id',
                        sortName:'Id',
                        sortOrder:'desc',
                        remoteFilter: true,
                        singleSelect: true,
                        method: 'post',
                        pagination: true,
                        clientPaging:false,
                        striped:true,
         pageList: [15, 20, 50, 100, 500, 2000],
        filterRules: [],
        onClickCell: onClickCell,
                        onBeforeLoad: function () {
                        $('.enable-loader').removeClass('enable-loader')
                        },
                        onLoadSuccess: function (data) {
                          $("button[name*='deleterowbutton']").prop('disabled', true);
                          $("button[name*='savechangesbutton']").prop('disabled', true);
                        },
                        onCheck: function () {
                          $("button[name*='deleterowbutton']").prop('disabled', false);
                        },
                        onUncheck: function () {
                           const checked = $(this).datagrid('getChecked').length > 0;
                           $("button[name*='deleterowbutton']").prop('disabled', !checked);
                        },
                        onCheckAll: function (rows) {
                          if(rows.length > 0){
                            $("button[name*='deleterowbutton']").prop('disabled', false);
                          }
                        },
                        onUncheckAll: function () {
                         $("button[name*='deleterowbutton']").prop('disabled', true);
                        },
                        onSelect: function(index,row) {
                           watermanualrecord = row;
                        },
                        frozenColumns: [[
                         /*开启CheckBox选择功能*/
                         { field: 'ck', checkbox: true },
                        ]],
                        columns: [[
                           {    /*表名*/
                 field:'Name',
                 title:'@Html.DisplayNameFor(model => model.Name)',
                 width:150,
                 hidden:false,
                 sortable:true,
                 resizable:true
            },
            {    /*表号*/
                 field:'meterId',
                 title:'@Html.DisplayNameFor(model => model.meterId)',
                 width:120,
                 hidden:false,
                 sortable:true,
                 resizable:true
            },


            {    /*出线名称*/
                 field:'Name1',
                 title:'@Html.DisplayNameFor(model => model.Name1)',
              width: 150,
                 hidden:false,
                 sortable:true,
                 resizable:true
                          },

            {    /*出线名称*/
              field:'Address',
                 title:'@Html.DisplayNameFor(model => model.Address)',
                 width:160,
                 hidden:false,
                 sortable:true,
                 resizable:true
                          },
            {   /*抄表日期*/
                field:'RecordDate',
                title:'@Html.DisplayNameFor(model => model.RecordDate)',
                width:160,
                align:'right',
                hidden:false,
                formatter:dateformatter,
                sortable:true,
              resizable: true,
                editor:{
                          type:'datebox',
                          options:{
                           prompt:'@Html.DescriptionFor(model => model.RecordDate)',
                             required:true,
                            formatter: dateformatter,
                             }
                       },
            } ,
            {    /*本期读数*/
                 field:'Water',
                 title:'@Html.DisplayNameFor(model => model.Water)',
                 width:150,
                 align:'right',
                 hidden:false,
                formatter:numberformatter,
                sortable:true,
              resizable: true,
                editor:{
                          type:'numberbox',
                          options:{
                           prompt:'@Html.DescriptionFor(model => model.Water)',
                             required:true,
                            formatter: numberformatter,
                            parser: parsernumber,
                             }
                       },
            },

            {    /*备注*/
                 field:'Remark',
                 title:'@Html.DisplayNameFor(model => model.Remark)',
                 width:260,
                 hidden:false,
                 sortable:true,
              resizable: true,
                  editor:{
                          type:'textbox',
                          options:{
                             id:'editor_Remark',
                             prompt:'@Html.DescriptionFor(model => model.Remark)',
                             required:false,
                             }
                       },
            },
                 ]]
           }).datagrid('enableFilter',[
                {   /*本期读数*/
                      field: 'Water',
                      type: 'numberbox',
                      op:['equal','notequal','less','lessorequal','greater','greaterorequal']
                  },
                {     /*抄表日期*/
                      field: 'RecordDate',
                      type: 'dateRange',
                      options: {
                      }
                  },
           ])
           .datagrid('load', '/WaterManualRecords/GetData');

     });

  </script>



}


